package com.cmos.um.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cmos.um.beans.CtiMessage;
import com.cmos.um.beans.CtiMessageExtends;
import com.cmos.um.iservice.ICtiMessageSV;
import com.cmos.um.iservice.IAgentSV;
import com.cmos.um.utils.Result;
import com.cmos.um.utils.ResultUtil;
import com.cmos.um.utils.WSContent;
import com.cmos.um.utils.WSRtnJsonCtx;
import com.cmos.um.utils.exception.ExceptionEnum;
import com.cmos.um.utils.http.RestClientHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class AgentSVImpl implements IAgentSV {

    private final static Logger logger = LoggerFactory.getLogger(AgentSVImpl.class);
    @Autowired
    private ICtiMessageSV ctiMessageservice;

    @Autowired
    private RestClientHttpRequest clien;

    @Override
    public Result taskAgentState(JSONObject params) {
        JSONObject toCC = new JSONObject();//要返回的信息
        JSONObject tolistMember = new JSONObject();
        JSONObject jsonParams = params.getJSONObject("params");
        String taskId = jsonParams.getString("serviceId");

        CtiMessageExtends ctiMessageExtends = ctiMessageservice.queryCtimessageBytaskId(taskId);//从数据库查出cti
        if (ctiMessageExtends == null) {
            return ResultUtil.error("-9999", "没有找到此任务号对应的cti");
        }
        //构建数据发送给cti
        tolistMember.put("startItem", "0");
        tolistMember.put("maxItem", "500");
        tolistMember.put("belongType", "0");
        tolistMember.put("serviceType", "3");
        tolistMember.put("vccId", WSContent.companyNo);
        tolistMember.put("serviceId", ctiMessageExtends.getTaskXfId());

        String ctiIp = ctiMessageExtends.getCtiIp();
        WSRtnJsonCtx resultListMember = clien.doPost(WSContent.servUrl, ctiIp, "listMember", WSContent._OTHER, tolistMember);
        if (!"0".equals(resultListMember.getRescode())) {
            logger.error("调用查询成员列表接口失败，错误信息为：" + resultListMember.getResJsonObj().toJSONString());
            return ResultUtil.error("-9999", "调用cti接口失败");
        }
        //取出所有的cti信息
        JSONArray agentList = resultListMember.getOutputObj().getJSONArray("contextArray");
        if (agentList == null || agentList.isEmpty()) {
            logger.error("没有查询出的坐席列表");
            return ResultUtil.error("-9999", "此任务号下没有查到坐席！");
        }
        JSONArray agents = new JSONArray();
        for (Object list : agentList) {
            JSONObject agentInfo = (JSONObject) list;
            String agentId = agentInfo.getString("agentId");
            JSONObject agentStatu = new JSONObject();
            agentStatu.put("agentId", agentId);
            WSRtnJsonCtx resultListAgent = clien.doPost(WSContent.agentUrl, ctiIp, "findAgent", WSContent._OTHER, agentStatu);
            if (!"0".equals(resultListAgent.getRescode())) {
                logger.error("调用查询坐席列表接口失败，错误信息为：" + resultListAgent.getResJsonObj().toJSONString());
                return ResultUtil.error("-9999", "调用cti接口失败");
            }
            JSONObject agent = new JSONObject();
            agent.put("agentId", agentId);
            agent.put("agentState", resultListAgent.getContextObj().getString("agentState"));
            agents.add(agent);
        }
        toCC.put("serviceId", taskId);
        toCC.put("agents", agents);
        return ResultUtil.success("0", "成功", toCC);
    }

    /**
     * 向所有的cti新增坐席
     *
     * @param params
     * @return
     */
    @Override
    public Result addAgent(JSONObject params) {
        List<CtiMessage> listCtiMessage = ctiMessageservice.queryAll();
        JSONObject Jparams = params.getJSONObject("params");
        JSONArray sendParams = new JSONArray();
        JSONObject sendParam = new JSONObject();
        ExceptionEnum rtnMsg = ExceptionEnum.OK;
        for (CtiMessage ctiInfo : listCtiMessage) {
            sendParam.put("agentId", Jparams.getString("agentId"));
            String ctiIp = ctiInfo.getCtiIp();
            logger.info("向" + ctiIp + "cti查询坐席");
            WSRtnJsonCtx listResult = clien.doPost(WSContent.agentUrl, ctiIp, "findAgent", WSContent._OTHER, sendParam);
            sendParam.put("ctiId", ctiInfo.getCtiId());
            sendParam.put("agentPasswd", Jparams.getString("agentPasswd"));
            sendParams.add(sendParam);
            //如果查到此坐席号号则直接返回
            if (listResult.getContextObj() != null) {
                rtnMsg = ExceptionEnum.AGENT_ADDER;
                continue;
            } else {
                logger.info("向" + ctiIp + "cti添加坐席");
                WSRtnJsonCtx result = clien.doPost(WSContent.agentUrl, ctiIp, "operateAgent", WSContent._SAVE, Jparams);
                if (!"0".equals(result.getRescode())) {
                    logger.error("调用新增坐席列表接口失败，错误信息为：" + result.getResJsonObj().toJSONString());
                    return ResultUtil.error(ExceptionEnum.CTI_ERROR);
                }

                JSONObject agentFunc = new JSONObject();
                agentFunc.put("agentId",Jparams.getString("agentId"));
                agentFunc.put("vccId",Jparams.getString("vccId"));
                agentFunc.put("outCall","1");
                agentFunc.put("keepCall","1");
                agentFunc.put("activeOver","1");
                agentFunc.put("forwardFlag","1");
                agentFunc.put("meetingFlag","1");
                agentFunc.put("askingFlag","1");
                agentFunc.put("passFlag","1");

                WSRtnJsonCtx agentFuncResult = clien.doPost(WSContent.vccUrl,  ctiIp, "operateAgentFunc", WSContent._SAVE,agentFunc);

                if (!"0".equals(agentFuncResult.getRescode())) {
                    logger.error("调用新增坐席功能接口失败，错误信息为：" + agentFuncResult.getResJsonObj().toJSONString());
                    return ResultUtil.error(ExceptionEnum.CTI_ERROR);
                }
            }
        }
        return ResultUtil.success(sendParams, rtnMsg);
    }

}
